package com.chuangsi.project.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.IService;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chuangsi.common.utils.Assert;
import com.chuangsi.framework.aspectj.lang.annotation.DataScope;
import com.chuangsi.project.admin.domain.Plan;
import com.chuangsi.project.admin.dto.admin.plan.PlanPageQueryReqDto;
import com.chuangsi.project.admin.dto.admin.plan.PlanPageQueryResDto;
import com.chuangsi.project.admin.dto.admin.plan.PlanSetReqDto;
import com.chuangsi.project.admin.mapper.PlanMapper;
import com.chuangsi.project.admin.service.IPlanService;
import com.chuangsi.project.admin.service.OrderService;
import com.chuangsi.project.system.domain.SysDept;
import com.chuangsi.project.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

import static com.chuangsi.project.system.service.impl.SysDeptServiceImpl.CUSTOMER_DEPT_ID;

/**
 * <p>
 * 销售计划 服务实现类
 * </p>
 *
 * @author ywb
 * @since 2025-03-06
 */
@Service
public class PlanServiceImpl extends ServiceImpl<PlanMapper, Plan> implements IPlanService {

    @Autowired
    private ISysDeptService sysDeptService;

    @Override
    @DataScope(deptAlias = "sd")
    public List<PlanPageQueryResDto> pageQuery(PlanPageQueryReqDto dto) {
        return baseMapper.pageQuery(dto);
    }

    @Override
    public void setPlan(PlanSetReqDto req) {
        SysDept sysDept = sysDeptService.selectDeptById(req.getDeptId());
        Assert.notNull(sysDept,"未找到部门");
//        Assert.isTrue(sysDept.getDeptId().equals(CUSTOMER_DEPT_ID),"客户部门不能设置计划");
        Plan plan = getOne(Wrappers.lambdaQuery(Plan.class).eq(Plan::getYm,req.getYm()).eq(Plan::getDeptId,req.getDeptId()));
        if(plan == null){
            plan = new Plan();
            plan.setYm(req.getYm());
            plan.setDeptId(req.getDeptId());
            plan.setCreateTime(LocalDateTime.now());
            plan.setYear(Integer.parseInt(StrUtil.splitTrim(req.getYm(),"-").get(0)));
            plan.setMonth(Integer.parseInt(StrUtil.splitTrim(req.getYm(),"-").get(1)));
            StrUtil.splitTrim(req.getYm(),"-").get(1);
        }
        plan.setMoneyGoal(req.getMoneyGoal());
        plan.setNumGoal(req.getNumGoal());
        plan.insertOrUpdate();
    }

    @Override
    public Plan getDeptMonthPlan(Long deptId, String month) {
        return getOne(Wrappers.lambdaQuery(Plan.class).eq(Plan::getYm,month).eq(Plan::getDeptId,deptId));
    }
}
